package cn.com.ourclass.webviewnew.web.client;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hc.framework.utils.CheckNetwork;

import cn.com.ourclass.webviewnew.web.WebViewNewActivity;

/**
 * Created by HuHaiqin on 2017/11/16.
 */

public class MyWebViewClient extends WebViewClient{

    private WebViewNewActivity mActivity;

    public MyWebViewClient(WebViewNewActivity mActivity) {
        this.mActivity = mActivity;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        if (mActivity.sonicSession != null) {
            mActivity.sonicSession.getSessionClient().pageFinish(url);
        }

        if (!CheckNetwork.isNetworkConnected(mActivity)) {
            //没有网络链接了
        }
        // html加载完成之后，添加监听图片的点击js函数
        mActivity.addImageClickListener();
    }

    @TargetApi(21)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return shouldInterceptRequest(view, request.getUrl().toString());
    }

    /**
     * 检测网页加载的互联网资源，防止电信运营商
     * @param view
     * @param url
     * @return
     */
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        if (mActivity.sonicSession != null) {
            return (WebResourceResponse) mActivity.sonicSession.getSessionClient().requestResource(url);
        }
        return null;
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        Log.e("hhq",url);
        //处理URL的处理
        if (url.startsWith(WebView.SCHEME_TEL) || url.startsWith("sms:") || url.startsWith(WebView.SCHEME_MAILTO)) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                mActivity.startActivity(intent);
            } catch (ActivityNotFoundException ignored) {
            }
            return true;
        }
        return false;
    }


    // 视频全屏播放按返回页面被放大的问题
    @Override
    public void onScaleChanged(WebView view, float oldScale, float newScale) {
        super.onScaleChanged(view, oldScale, newScale);
        if (newScale - oldScale > 7) {
            view.setInitialScale((int) (oldScale / newScale * 100)); //异常放大，缩回去。
        }
    }



}
